
package com.hefeng.wx.controller;


import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hefeng.common.core.domain.MapEntity;
import com.hefeng.common.core.utils.AmapUtil;
import com.hefeng.common.core.utils.file.FileUtils;
import com.hefeng.common.core.utils.oss.AliOssUtil;
import com.hefeng.common.core.web.domain.AjaxResult;
import com.hefeng.common.core.config.BaseStaticParameter;
import com.hefeng.wx.controller.entity.ParamEntity;
import com.hefeng.wx.domain.WxResidence;
import com.hefeng.wx.domain.WxUser;
import com.hefeng.wx.service.WxResidenceService;
import com.hefeng.wx.service.WxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.hefeng.common.core.utils.EmptyUtils;
import com.hefeng.common.core.utils.HttpRequester;
import com.hefeng.common.core.utils.HttpRespons;

import java.io.IOException;
import java.util.*;

/**
 * 微信小程序登录
 *
 * @author Mark sunlightcs@gmail.com
 */
@Slf4j
@RestController
@RequestMapping("/resident/index")
@Api(tags="小程序登录接口")
public class ApiLoginController {
    @Autowired
    private WxResidenceService wxResidenceService;
    @Autowired
    WxUserService wxUserService;
    private static HttpRequester requester = new HttpRequester();
    @RequestMapping(value = "/login",produces = "application/json;charset=UTF-8")
    @ApiOperation("登录")
    public AjaxResult login(@RequestBody JSONObject userLogin){
        Map<String,Object> data=new HashMap<String,Object>();
        JSONObject obj=new JSONObject();
        //微信小程序验证
        log.info( "微信用户登录" );
        String code =userLogin.getString("code");
        Map<String,Object> dataMap = new HashMap<String, Object>( );
        Map<String,String> map = new HashMap<String, String>( );
        //参数map
        map.put("appid", BaseStaticParameter.WXAPPID);
        map.put("secret",BaseStaticParameter.WXSECRET);
        map.put("code",code);
        //微信那边的接口，grant_type=authorization_code是固定的
        String url="https://api.weixin.qq.com/sns/jscode2session?appid="+BaseStaticParameter.WXAPPID+
                "&secret="+BaseStaticParameter.WXSECRET+"&js_code="+code+"&grant_type=authorization_code";
        try {
            //微信后台验证
            HttpRespons ret = requester.sendPost(url, map);
            obj=JSONObject.parseObject( ret.getContent());
            String openid=obj.getString("openid");
            System.out.println(openid);
            //获取用户信息
            WxUser user=wxUserService.getWxuserById(openid);
            if(EmptyUtils.isNotEmpty(user)){
                data.put("user",user);
                return AjaxResult.success("登录成功！",data);
            }
            return AjaxResult.success(obj);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("500","登录超时，请退出后重新登录！");
        }
    }
    /**
    * 方法说明: 上传用户头像
    * @Param: []
    * @return: com.hefeng.common.core.web.domain.AjaxResult
    * @Author: huzh
    * @Date: 2022/9/2
    */
    @ApiOperation("上传图片接口")
    @ResponseBody
    @RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    public AjaxResult uploadPhoto(@RequestParam(value = "file") MultipartFile[] files){

        List<Map>list =new ArrayList<>();
        try {
        if(EmptyUtils.isEmpty(files)){
            System.out.println("文件为空！");
            return AjaxResult.error("文件不能为空",false);
        }

        for (MultipartFile file:files){
        Map map=  new HashMap<>();
        String fileName = file.getOriginalFilename();  // 文件名
        String filePath="";
        if(FileUtils.isImageFile(fileName.substring(fileName.indexOf("."),fileName.length()))){
            filePath="pic";
        }
        if(fileName.substring(fileName.indexOf("."),fileName.length()).equals(".mp4")){
            filePath="video";
        }
        if(fileName.substring(fileName.indexOf("."),fileName.length()).equals(".mp3")){
            filePath="MP3";
        }

        //创建输出文件对象
        String fname = UUID.randomUUID().toString()+ FileUtils.getName(fileName);
        AliOssUtil ossUtil=new AliOssUtil();
        String url = ossUtil.uploadFile(file.getInputStream(),"gas/order/"+filePath+"/"+fname);
        map.put("url",url);
        list.add(map);
        }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success("上传成功",list);
    }
    /**
    * 方法说明: 获取小区信息
    * @Param: []
    * @return: com.hefeng.common.core.web.domain.AjaxResult
    * @Author: huzh
    * @Date: 2022/9/2
    */
    @RequestMapping(value = "/getResidenceList",produces = "application/json;charset=UTF-8")
    @ApiOperation("获取小区接口")
    public AjaxResult getResidenceList(@RequestBody ParamEntity paramEntity){
       Map<String,Object> dataMap=new HashMap<>();
       //经纬度匹配街道
        MapEntity mapEntity=AmapUtil.getTowncodeByLocation(paramEntity.getLongitude(),paramEntity.getLatitude());
        if(EmptyUtils.isNotEmpty(mapEntity)&&EmptyUtils.isNotEmpty(paramEntity.getLongitude())&&EmptyUtils.isNotEmpty(paramEntity.getLatitude())){
            String code=mapEntity.getTowncode();
            QueryWrapper<WxResidence> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id","name").eq("towncode",code);
            List dataList=wxResidenceService.listMaps(queryWrapper);
            dataMap.put("residenceList",dataList);
        }else {
            //查询全部
            QueryWrapper<WxResidence> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id","name");
            List<Map<String, Object>> dataList=wxResidenceService.listMaps(queryWrapper);
            dataMap.put("residenceList",dataList);
        }
        return  AjaxResult.success("获取成功！",dataMap);
    }

}
